import axios from 'axios'
import config from '../config'
import { getTokenAsync } from './accessToken'

const service = axios.create({
  baseURL: config.baseURL,
  timeout: config.timeout,
  headers: {
    Accept: 'application/json, text/plain, application/octet-stream, */*',
    'Content-Encoding': 'gzip'
  }
})

service.interceptors.request.use(async (request) => {
  // const locale = localStorage.getItem(config.localeTableName) || "zh-TW";
  // if (locale) {
  //   request.headers["Accept-Language"] = locale;
  // }

  const token = await getTokenAsync()
  if (token != null) {
    request.headers.Authorization = 'Bearer ' + token
  }

  return request
})

service.interceptors.response.use(
  (response) => {
    if (
      response.data instanceof Blob ||
      response.data.code == 200 ||
      typeof response.data.result == 'undefined'
    ) {
      return response.data
    } else {
      return Promise.reject(response.data.error)
    }
  },
  (error) => {
    if (error.response.status == 403 || error.response.status == 401) {
      window.location.href = '/login'
      return Promise.reject(error)
    }

    return Promise.reject(String(error))
  }
)

export default service
